#include "pch.h"
#include "BaseInc.h"
#include "HttpClient.h"
#include <ws2tcpip.h>

string HttpClient::RestGet(string scheme, string host, int port, string base, string param)
{
	if (scheme == "https")
		clnt = &sslclient;
	else
		clnt = &client;

	string hostIp = getHostByHostName(host);
	clnt->Init(hostIp, port);
	if (!client.IsConnect())
	{
		return "FailConnect";
	}
	Request req;
	req.SetClient(clnt);
	req.BuildGetRequest(host, port, base, param);
	Response resp;
	ByteData recvBuff;
	clnt->ReceiveAll(recvBuff);
	resp.LoadResponseData(recvBuff);
	clnt->Close();
	return resp.GetContent();
}
string HttpClient::RestPost(string scheme, string host, int port, string base, string param)
{
	if (scheme == "https")
		clnt = &sslclient;
	else
		clnt = &sslclient;
	string hostIp = getHostByHostName(host);
	clnt->Init(hostIp, port);
	if (!client.IsConnect())
	{
		return "FailConnect";
	}
	Request req;
	req.SetClient(clnt);
	req.BuildPostRequest(host, port, base, param);
	Response resp;
	ByteData recvBuff;
	clnt->ReceiveAll(recvBuff);

	resp.LoadResponseData(recvBuff);
	clnt->Close();
	return resp.GetContent();
}

std::string HttpClient::getHostByHostName(std::string hostName)
{
	struct hostent* ent;
	int  i = 0;
	char* ptr = const_cast<char*> (hostName.data());
	char src[32] = { 0 };
	if ((ent = gethostbyname(ptr)) != NULL) {
		InetNtopA(ent->h_addrtype, ent->h_addr_list[0], src, 32);
	}
	return src;
}
